package com.banwoqiche.security;

import com.banwoqiche.mapper.SysRoleMapper;
import com.banwoqiche.SysMenu;
import com.banwoqiche.SysRole;
import com.banwoqiche.MySecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @time: 2022-03-30 10:36
 */
@Component
public class MySecuritySuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    private CRankMapper CRankMapper;

    @Autowired
    public void setCRankMapper(com.cafe.bwqc.mapper.CRankMapper CRankMapper) {
        this.CRankMapper = CRankMapper;
    }

    /**
     *
     * @param request
     * @param response
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //获取返回的对象
        MySecurityUser backUser = (MySecurityUser) authentication.getPrincipal();
        //根据id查询它的所有权限
        List<CRank> cRankList = CRankMapper.getRankMenuByuserid(backUser.getUserId());
        //创建存放用户权限的表
        Set<String> userPermisson = new HashSet<>();
        //遍历存入
        cRankList.forEach(cRank -> {
            List<CMenus> sss = cRank.getcMenusList();
            List<String> ddd = sss.stream().map(CMenus::getmPerms).collect(Collectors.toList());
            userPermisson.addAll(ddd);
        });
        List<SimpleGrantedAuthority> authorityList = userPermisson.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        SecurityContextHolder
                .getContext()
                .setAuthentication(
                        new UsernamePasswordAuthenticationToken(
                                backUser,
                                authentication.getAuthorities(),
                                authorityList));
    }
}

